/*
 * @Author: libing 9852442+liu-sheng-8667@user.noreply.gitee.com
 * @Date: 2024-05-23 20:46:26
 * @LastEditors: xuezhuangzhuang xzz6996@qq.com
 * @LastEditTime: 2024-06-04 22:17:39
 * @FilePath: \crm\config\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
	getToken
} from "@/config/storage";

const DURATION = 2000;
/**
 * 统一请求的地方
 * @param {*} path 后端路径
 * @param {*} method 请求方式
 * @param {*} params 参数
 * @param {*} header 扩充请求头
 * @param {*} needSucMsg 接口成功之后是否需要弹出成功信息
 * @param {*} needDeepData 是否返回res.data.data, 否则返回res.data
 * @returns promise
 */

export function service({
	path = "",
	method = "POST",
	params = {},
	header = {},
	needSucMsg = false,
	needDeepData = true,
	timeout = 10000,
	url = "",
}) {
	console.log(header);
	let promise = new Promise((resolve, reject) => {
		uni.request({
			url: process.env.VUE_APP_BASE_URL + path + url,
			data: {
				...params,
			},
			dataType: "json",
			header: {
				"Tenant-Id": 1,
				// request拦截器
				token: getToken(), // 让每个请求携带自定义token 请根据实际情况自行修改
				"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", //自定义请求头信息
				Authorization: "Bearer " + getToken(),
				...header,
			},
			timeout,
			method: method,
			success(res) {
				console.log("返回结果：", res.data);
				let {
					msg,
					code
				} = res.data;
				code = code || 0
				if ([0, "0000"].includes(code)) {
					if (needSucMsg) {
						uni.showToast({
							icon: "none",
							title: msg,
						});
					}
					// 成功
					resolve(needDeepData ? res.data.data : res.data);
				} else {
					uni.showToast({
						icon: "none",
						title: msg || "失败",
						duration: DURATION,
					});
					reject(res.data);
					if (code === 1) {
						uni.clearStorageSync()
						uni.reLaunch()
						uni.navigateTo({
							url: "/pagesecharts/login/login"
						})
					}
				}
			},
			fail(res) {
				const msg = res.data?.message || res.errMsg || "失败";
				uni.showToast({
					icon: "none",
					title: msg,
					duration: DURATION,
				});
				reject(res);
				console.error("错误结果：", res);
			},
		});
	});
	return promise;
}